package com.hongtech.modules.oss;

import com.hongtech.common.OssException;
import com.hongtech.common.utils.DateUtils;
import com.hongtech.common.utils.FileUtil;
import com.hongtech.common.utils.UUIDUtil;
import com.hongtech.framework.config.OssConfig;
import org.apache.commons.io.IOUtils;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;

/**
 * 本地存储
 */
public class LocalOssService extends OssService {

    LocalOssService(OssConfig config) {
        this.config = config;
    }

    @Override
    public SysUploadFile upload(byte[] data, String path, boolean isPublic) {
        String date = DateUtils.dateTime();
        String realPath = getRealPath(path, date);
        try (FileOutputStream os = new FileOutputStream(realPath)) {
            FileCopyUtils.copy(data, os);
            boolean localEnd = config.getLocalDomain().endsWith("/");
            String localDomain = localEnd ? config.getLocalDomain() : config.getLocalDomain() + "/";
            String filePath = config.getLocalPrefix() + "/" + date + "/" + path;
            SysUploadFile sysFile = new SysUploadFile();
            sysFile.setFilePath(filePath);
            sysFile.setFileUrl(localDomain + filePath);
            sysFile.setFileName(path);
            sysFile.setFileType(getFileType(path));
            sysFile.setOssType(OssTypeEnum.LOCAL.getValue());
            return sysFile;
        } catch (Exception e) {
            throw new OssException("上传本地文件失败", e);
        }
    }

    @Override
    public SysUploadFile upload(InputStream is, String path, boolean isPublic) {
        try {
            return upload(IOUtils.toByteArray(is), path, isPublic);
        } catch (IOException e) {
            throw new OssException("上传本地文件失败", e);
        }
    }

    @Override
    public SysUploadFile uploadSuffix(byte[] data, String suffix, boolean isPublic) {
        return upload(data, getPath(suffix), isPublic);
    }

    @Override
    public SysUploadFile uploadSuffix(InputStream inputStream, String suffix, boolean isPublic) {
        return upload(inputStream, getPath(suffix), isPublic);
    }

    @Override
    public void delete(String path) {
        FileUtil.delete(Paths.get(config.getLocalUploadDir() + File.separator + path));
    }

    private String getPath(String suffix) {
        return UUIDUtil.generateShortUuid() + suffix;
    }

    private String getRealPath(String path, String pre) {
        String dir = config.getLocalUploadDir() + File.separator + config.getLocalPrefix() + File.separator + pre;
        if (!FileUtil.exists(dir)) {
            try {
                FileUtil.createDir(dir);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return dir + File.separator + path;
    }

}
